package com.gitee.wsl.platform.concurrent

import java.lang.Thread as JvmThread
import kotlinx.coroutines.CloseableCoroutineDispatcher
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.newSingleThreadContext


internal actual class InternalThreadId(private val thread: JvmThread) {
    override fun equals(other: Any?): Boolean {
        return this === other || (other is InternalThreadId && thread == other.thread)
    }

    override fun hashCode() = thread.hashCode()
    override fun toString() = thread.toString()
}


internal actual class InternalThread {
    actual companion object {
        actual fun getId(): InternalThreadId =
            InternalThreadId(JvmThread.currentThread())

        actual fun sleepMs(millis: Int) {
            JvmThread.sleep(millis.toLong())
        }
    }
}


/**
 * Creates a coroutine execution context using a single thread.
 *
 * **NOTE: The resulting [CloseableCoroutineDispatcher] owns native resources (its thread).
 * Resources are reclaimed by [CloseableCoroutineDispatcher.close].**
 * @param name The name of the thread to be created.
 */
@OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class)
actual fun singleThreadDispatcher(name: String): CloseableCoroutineDispatcher = newSingleThreadContext(name)

/**
 * Creates a coroutine execution context using a thread pool.
 *
 * **NOTE: The resulting [CloseableCoroutineDispatcher] owns native resources (its thread).
 * Resources are reclaimed by [CloseableCoroutineDispatcher.close].**
 */
@OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class)
actual fun threadPoolDispatcher(numberOfThreads: UInt, name: String): CloseableCoroutineDispatcher = newFixedThreadPoolContext(numberOfThreads.toInt(), name)
